package com.atguigu.gulimall.order.config;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 如果设置错误需要删掉错误的Queue重启服务即可，重启服务不会覆盖原有的Queue
 */
@Configuration
public class MyMQConfig {

//    @RabbitListener(queues = {"order.release.order.queue"})
//    public void ListenQueue(Channel channel, Message message, OrderEntity orderEntity) throws IOException {
//        //因为配置了手动ack，所有这里需要签收消息
//        //basicAck(long deliveryTag, boolean multiple)
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        System.out.println("手动过期的订单信息，准备关闭订单："+orderEntity.getOrderSn());
//    }

    @Bean
    public Queue OrderDelayQueue(){
        Map<String,Object> map = new HashMap<>();
        //死信路由exchange
        map.put("x-dead-letter-exchange","order-event-exchange");
        //死信routing-key
        map.put("x-dead-letter-routing-key","order.release.order");
        //time to live
        map.put("x-message-ttl",60000);

        //持久化，排它
        //Queue(String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        return new Queue("order.delay.order",true,false,false,map);
    }

    @Bean
    public Queue OrderReleaseOrderQueue(){
        return new Queue("order.release.order.queue",true,false,false,null);
    }

    //选用topic类型交换机是因为需要binding多个队列
    @Bean
    public Exchange OrderEventExchange(){
        //TopicExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments)
        return new TopicExchange("order-event-exchange",true,false,null);
    }

    @Bean
    public Binding OrderCreateOrder(){
        //Binding(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, Map<String, Object> arguments)
        return new Binding("order.delay.order", Binding.DestinationType.QUEUE,"order-event-exchange","order.create.order",null);
    }

    @Bean
    public Binding OrderReleaseOrder(){
        return new Binding("order.release.order.queue", Binding.DestinationType.QUEUE,"order-event-exchange","order.release.order",null);
    }

    /**
     * 增加绑定规则,订单释放直接与解锁库存进行绑定
     * 订单状态因为故障未修改，导致无法锁库存
     */
    @Bean
    public Binding OrderReleaseOrderOtherBinding(){
        return new Binding("stock.release.stock.queue",Binding.DestinationType.QUEUE,"order-event-exchange","order.release.other.#",null);
    }



}
